package com.dingyh.shopwebbackground.controller;


import com.dingyh.shopwebbackground.entity.Business;
import com.dingyh.shopwebbackground.entity.Commodity;
import com.dingyh.shopwebbackground.entity.CommodityType;
import com.dingyh.shopwebbackground.service.BusinessService;
import com.dingyh.shopwebbackground.service.CommodityService;
import com.dingyh.shopwebbackground.service.CommodityTypeService;
import com.dingyh.shopwebbackground.util.CommonResult;
import com.dingyh.shopwebbackground.util.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dingyuhan
 * @since 2023-02-14
 */
@RestController
@RequestMapping("/commodity")
@CrossOrigin
public class CommodityController {

    @Autowired
    CommodityService commodityService;

    @Autowired
    CommodityTypeService commodityTypeService;

    @Autowired
    BusinessService businessService;

    /**
     * 全部商品
     * @param type
     * @param commodityType
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/allGoods")
    public CommonResult<Object> allGoods(String type,CommodityType commodityType,
                                         @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("type",type);
        map.put("typeUseOne",commodityType.getTypeUseOne());
        map.put("typeUseTwo",commodityType.getTypeUseTwo());
        map.put("typeEatOne",commodityType.getTypeEatOne());
        map.put("typeEatTwo",commodityType.getTypeEatTwo());
        map.put("typeEatThree",commodityType.getTypeEatThree());
        List<Commodity> commodities = commodityService.allGoods(map);
        PageInfo<Commodity> page = new PageInfo<>(commodities);
        return new CommonResult(200,"",page);
    }

    /**
     * 后端管理的商品管理页
     * @param companyId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("allGoodsByCompany")
    public CommonResult<Object> allGoodsByCompany(String companyId ,
                                                  @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("companyid",companyId);
        List<Commodity> commodities = commodityService.allGoodsByCompany(map);
        commodities.forEach(commodity -> {
            CommodityType commodityType = commodityTypeService.selectByGoodsId(commodity.getId());
            if (commodity.getType().equals("器械保健")){
                commodity.setTypeUseOne(commodityType.getTypeUseOne());
                commodity.setTypeUseTwo(commodityType.getTypeUseTwo());
            }else {
                commodity.setTypeEatOne(commodityType.getTypeEatOne());
                commodity.setTypeEatTwo(commodityType.getTypeEatTwo());
                commodity.setTypeEatThree(commodityType.getTypeEatThree());
            }
        });
        PageInfo<Commodity> page = new PageInfo<>(commodities);
        return new CommonResult(200,"",page);
    }


    @RequestMapping("allGoodsBySaleMonth")
    public CommonResult<Object> allGoodsBySaleMonth(String companyId ,
                                                  @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("companyid",companyId);
        List<Commodity> commodities = commodityService.allGoodsBySaleMonth(map);
        commodities.forEach(commodity -> {
            CommodityType commodityType = commodityTypeService.selectByGoodsId(commodity.getId());
            if (commodity.getType().equals("器械保健")){
                commodity.setTypeUseOne(commodityType.getTypeUseOne());
                commodity.setTypeUseTwo(commodityType.getTypeUseTwo());
            }else {
                commodity.setTypeEatOne(commodityType.getTypeEatOne());
                commodity.setTypeEatTwo(commodityType.getTypeEatTwo());
                commodity.setTypeEatThree(commodityType.getTypeEatThree());
            }
        });
        PageInfo<Commodity> page = new PageInfo<>(commodities);
        return new CommonResult(200,"",page);
    }



    /**
     * 主页推送的商品
     * @return
     */
    @RequestMapping("/isPushHome")
    public CommonResult isPushHome(@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        List<Commodity> commodity = commodityService.isPushHome(map);
        PageInfo<Commodity> page = new PageInfo<>(commodity);
        return new CommonResult(200,"",page);
    }

    /**
     * 轮播图推送的商品
     * @return
     */
    @RequestMapping("/isPushImg")
    public CommonResult isPushImg(@RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("ispush","1");
        List<Commodity> commodity = commodityService.isPushHome(map);
        PageInfo<Commodity> page = new PageInfo<>(commodity);
        return new CommonResult(200,"",page);
    }

    @RequestMapping("/selectByName")
    public CommonResult selectByName(String type,String title, @RequestParam(defaultValue = "1",required = true )int pageIndex, @RequestParam(defaultValue = "10",required = true )int pageSize){
        PageHelper.startPage(pageIndex, pageSize);//初始化分页
        Map<String,Object> map = new HashMap<>();
        map.put("title",title);
        map.put("type",type);
        List<Commodity> commodity = commodityService.selectByName(map);
        PageInfo<Commodity> page = new PageInfo<>(commodity);
        return new CommonResult(200,"",page);
    }

    /**
     * 添加商品
     * @param commodity
     * @param commodityType
     * @return
     */
    @RequestMapping("/addGoods")
    public CommonResult addGoods(Commodity commodity, CommodityType commodityType){
        String idCurr = UUIDUtil.generator();
//        String typeIdCurr = UUIDUtil.generator();
        Business business = businessService.selectByUserId(commodity.getCompanyid());
        Commodity commodityCurr = Commodity.builder()
                .id(idCurr)
                .companyid(commodity.getCompanyid())
                .companyname(business.getSaleName())
                .price(commodity.getPrice())
                .title(commodity.getTitle())
                .timeAdd(System.currentTimeMillis())
                .detail(commodity.getDetail())
                .type(commodityType.getIfEat())
                .img(commodity.getImg())
                .ispush("0")
                .month(BigDecimal.valueOf(0))
                .stock(BigDecimal.valueOf(0))
                .build();
        CommodityType commodityTypeCurr = CommodityType.builder()
                .id(UUIDUtil.generator())
                .goodsId(idCurr)
                .ifEat(commodityType.getIfEat())
                .typeEatOne(commodityType.getTypeEatOne())
                .typeEatTwo(commodityType.getTypeEatTwo())
                .typeEatThree(commodityType.getTypeEatThree())
                .typeUseOne(commodityType.getTypeUseOne())
                .typeUseTwo(commodityType.getTypeUseTwo())
                .build();
        boolean result = commodityService.save(commodityCurr);
        boolean resultType = commodityTypeService.save(commodityTypeCurr);
        if (result && resultType) {
            return new CommonResult(200, "新增成功！", null);
        } else {
            return new CommonResult(500, "新增失败！", null);
        }
    }

    @RequestMapping("/selectGoods")
    public CommonResult<Object> selectGoods(String id){
        Commodity commodity = commodityService.selectGoods(id);
        if(commodity != null){
            return new CommonResult(200,"",commodity);
        }else {
            return new CommonResult(500,"您查找的商品不存在！");
        }
    }


    @RequestMapping("removeGoods")
    public CommonResult<Object> removeGoods(String id){
        if(commodityService.removeGoods(id)){
            return new CommonResult(200, "删除成功！", null);
        }else{
            return new CommonResult(500, "删除失败！", null);
        }
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadImageCommodity")
    public  CommonResult<Object> uploadImage(@RequestPart("file") MultipartFile file){
        String path = "D:/GraduatioProject/shopWeb-background/src/main/webapp/upload_images/commodity/";
        String picName = System.currentTimeMillis() + ".jpg";
        File targetFile = new File(path, picName);//文件地址-文件名字
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
//            e.printStackTrace();
            return new CommonResult<>(500,"",null);
        }
        return  new CommonResult<>(200,"", picName);
    }

}

